<script setup>
import Avatar from '@/components/Avatar.vue'
import {computed, onMounted, ref, watch} from "vue";
import {useRoute} from "vue-router";
import ArticleListItem from "@/views/Article/ArticleListItem.vue";
import UserInfoEdit from "@/views/UserCenter/UserInfoEdit.vue";
import {useUserStore} from "@/stores/index.js";
import {userAPI} from "@/apis/index.js";
import {ElMessage} from "element-plus";
import {Female} from "@element-plus/icons-vue";

const route = useRoute();

const userStore = useUserStore()
const userId = computed(() => parseInt(route.params.userId))

const userInfo = computed(() => userStore.userInfo || {})

const currentUserInfo = ref({})
const currentUserPost = ref({})
const currentUserBadge = ref({})

const loadingUserInfo = ref(false)
const loadingUserPost = ref(false)

const tabs = ref('post')

// 分页
const pagination = ref({
  totalCount: 0,
  pageSize: 5,
  pageNo: 1,
  pageTotal: 0
})

// 获取用户信息
const fetchUserInfo = async () => {
  const data = {
    userId: userId.value,
  }
  loadingUserInfo.value = true
  try {
    const response = await userAPI.getUserInfo(data)
    if (response.status === 'success') {
      currentUserInfo.value = response.data
    }
  } catch (error) {
    ElMessage.error('Failed to get user info')
    throw error
  } finally {
    loadingUserInfo.value = false
  }
}

// 获取用户徽章
const fetchUserBadges = async () => {
  try {
    const response = await userAPI.getUserBadges()
    if (response.status === 'success') {
      return response.data
    }
  } catch (error) {
    ElMessage.error('Failed to obtain user badge')
    throw error
  }
}

// 获取用户发布的帖子
const fetchUserPosts = async () => {
  const data = {
    userId: userId.value,
    pageNo: pagination.value.pageNo,
    pageSize: pagination.value.pageSize,
  }
  loadingUserPost.value = true
  try {
    const response = await userAPI.getUserPosts(data)
    if (response.status === 'success') {
      currentUserPost.value = response.data.list
      pagination.value = {
        pageNo: response.data.pageNo,
        pageSize: response.data.pageSize,
        totalCount: response.data.totalCount,
        pageTotal: response.data.pageTotal
      }
    }
  } catch (error) {
    console.log(error)
  } finally {
    loadingUserPost.value = false
  }
}

const changeTab = () => {

}

// 页码变化
const handlePageChange = (pageNo) => {
  pagination.value.pageNo = pageNo
  fetchUserPosts()
}

// 更新用户信息
const editUserInfoRef = ref(null);
const updateUserInfo = () => {
  editUserInfoRef.value.showEditUserInfoDialog(currentUserInfo.value)
};

const resetUserInfo = (data) => {
  userInfo.value = data
};

// 检测路由变化
watch(
    () => route.params.userId,
    (newVal, oldVal) => {
      if (newVal) {
        userId.value = newVal
      }
    },
    {immediate: true, deep: true}
);

onMounted(() => {
  fetchUserInfo()
  fetchUserPosts()
})

</script>

<template>
  <div class="container-body ucenter">
    <div class="user-banner">
      <router-link to="/" class="a-link">Home Page</router-link>
      <el-icon><ArrowRight/></el-icon>
      <span>User Info</span>
    </div>
    <div class="content-container">
      <div class="user-panel">
        <div class="skeleton" v-if="loadingUserInfo">
          <el-skeleton :row="3" animated></el-skeleton>
        </div>
        <div class="user-info" v-else>
          <div class="avatar-inner">
            <Avatar :src="currentUserInfo.avatar" :width="120"></Avatar>
          </div>
          <div class="info-inner">
            <div class="up-info">
              <div>
                <span class="username">{{ currentUserInfo.nickName }}</span>
                <span class="institution" v-if="currentUserInfo.institution">
                  <el-icon><OfficeBuilding /></el-icon>
                  {{ currentUserInfo.institution }}
                </span>
                <el-icon size="20" v-if="currentUserInfo.sex == 0">
                  <Male/>
                </el-icon>
                <el-icon size="20" v-if="currentUserInfo.sex == 1">
                  <Female/>
                </el-icon>
              </div>
              <div class="email">
                <span>Email: {{ currentUserInfo.email }}</span>
                <el-divider direction="vertical"></el-divider>
                <span>Register Time: {{currentUserInfo.joinTime}}</span>
              </div>
              <div class="signature">
                <span v-if="currentUserInfo.personDescription">{{ currentUserInfo.personDescription }}</span>
                <span v-else>This person hasn't written any description yet</span>
              </div>
            </div>
          </div>
          <div class="button-container">
            <div class="achievement-badge" v-if="currentUserInfo.badgeShow">
              <div class="badge-icon">
                <el-image fit="cover" :src="currentUserInfo.badgeShow.img" style="width: 60px;"></el-image>
              </div>
              <div class="badge-info">
                <span class="badge-title">{{currentUserInfo.badgeShow.name}}</span>
                <span class="badge-desc">{{currentUserInfo.badgeShow.description}}</span>
              </div>
            </div>
            <el-button type="primary" class="edit-info" v-if="userInfo.userId == currentUserInfo.userId" @click="updateUserInfo">Edit Info</el-button>
          </div>
        </div>
      </div>
      <div class="bottom-container">
        <div class="content-panel">
          <el-tabs
              v-model="tabs"
              type="border-card"
              class="content-tabs"
              @tab-click="changeTab"
          >
            <el-tab-pane name="post">
              <template #label>
              <span class="custom-tabs-label">
                <el-icon><Document/></el-icon>
                <span style="margin-left: 10px;">Post</span>
              </span>
              </template>
              <div class="article-list">
                <div class="skeleton" v-if="loadingUserPost">
                  <el-skeleton :row="3" animated></el-skeleton>
                </div>
                <template v-else>
                  <div v-if="currentUserPost.length > 0" v-for="item in currentUserPost">
                    <ArticleListItem :data="item"></ArticleListItem>
                  </div>
                  <div v-else>
                    <el-empty description="This person has not posted yet" />
                  </div>
                </template>
                <div class="pagination" v-if="pagination.pageTotal > 1">
                  <el-pagination
                      background
                      :total="pagination.totalCount"
                      v-model:current-page="pagination.pageNo"
                      layout="prev, pager, next"
                      style="text-align: right"
                      :page-size="pagination.pageSize"
                      @current-change="handlePageChange"
                  ></el-pagination>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="right-panel">
          <div class="last-login personal-data">
            <span class="name">Last login time</span>
            <span class="num">{{ currentUserInfo.lastLoginTime }}</span>
          </div>
          <div class="badge-num personal-data">
            <span class="name">Badge number</span>
            <span class="num">{{ currentUserInfo.badgeCount }}</span>
          </div>
          <div class="post-num personal-data">
            <span class="name">Post number</span>
            <span class="num">{{ currentUserInfo.postCount }}</span>
          </div>
          <div class="comment-num personal-data">
            <span class="name">Comment number</span>
            <span class="num">{{ currentUserInfo.commentCount }}</span>
          </div>
        </div>
      </div>
    </div>
    <UserInfoEdit
        ref="editUserInfoRef"
        @resetUserInfo="resetUserInfo"
    ></UserInfoEdit>
  </div>
</template>

<style scoped lang="scss">
.ucenter {
  width: 1300px;

  .user-banner {
    color: #9ba7b9;
    line-height: 35px;

    .icon-right {
      padding: 0px 5px;
    }
  }

  .content-container {
    background-color: #fff;

    .user-panel {
      padding: 20px;
      border-bottom: 1px solid #E4E7ED;

      .user-info {
        display: flex;
        align-items: flex-start;
        gap: 20px;

        .avatar-inner {
          flex-shrink: 0;
        }

        .info-inner {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: flex-start;
          height: 120px;

          .up-info {
            display: flex;
            flex-direction: column;
            gap: 8px;

            .username {
              font-size: 24px;
              font-weight: bold;
              color: #333;
              margin-right: 15px;
            }

            .institution {
              background-color: var(--el-color-primary);
              color: #fff;
              font-size: 18px;
              border-radius: 3px;
              display: inline-flex;
              align-items: center;
              justify-content: center;
              padding: 2px 5px;
              margin-right: 10px;
            }

            .email {
              span {
                font-size: 16px;
                color: #666;
              }
            }

            .signature {
              font-size: 18px;
              margin-top: 10px;
            }
          }
        }

        .button-container {
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          justify-content: flex-end;
          height: 120px;
          gap: 10px;
          
          .achievement-badge {
            display: flex;
            align-items: center;
            gap: 15px;
            background: linear-gradient(135deg, #FFF8DC 0%, #F0E68C 100%);
            border: 2px solid #FFD700;
            border-radius: 8px;
            padding: 8px 12px;
            box-shadow: 0 2px 8px rgba(255, 215, 0, 0.3);
            
            .badge-icon {
              display: flex;
              align-items: center;
              height: 60px;
            }
            
            .badge-info {
              display: flex;
              flex-direction: column;
              max-width: 500px;
              
              .badge-title {
                font-size: 20px;
                font-weight: bold;
                color: #B8860B;
                line-height: 1.2;
              }
              
              .badge-desc {
                font-size: 16px;
                color: #8B7355;
                line-height: 1.2;
              }
            }
          }
          
          .edit-info {
            font-size: 16px;
            width: 120px;
            height: 40px;
          }
        }
      }
    }

    .bottom-container {
      display: flex;
    }

    .content-panel {
      background-color: #fff;
      flex: 1;
      width: 1000px;

      .content-tabs {
        :deep(.el-tabs__item) {
          font-size: 24px;
          height: 50px;
        }

        .article-list {
          .pagination {
            padding: 10px 0px 10px 10px;
          }
        }
      }
    }

    .right-panel {
      width: 220px;
      padding: 20px;
      background-color: #FAFCFF;

      .last-login {
        display: flex;
        flex-direction: column;
      }
      .personal-data {
        margin-bottom: 10px;
        .name {
          font-size: 16px;
          font-weight: 400;
          color: #606266;
          margin-right: 10px;
        }

        .num {
          font-size: 26px;
          font-weight: 400;
          color: #909399;
        }
      }
    }
  }
}
</style>